<?php

namespace app\admin\controller\scanwork;

use app\common\controller\Backend;
use think\Db;
use think\Exception;

/**
 * 工资导出管理
 */
class WageExport extends Backend
{
    protected $model = null;
    protected $noNeedRight = ['index'];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\scanwork\Report;
        
        // 设置JS文件
        $this->view->assign('js', ['backend/scanwork/wage_export']);
    }

    /**
     * 导出页面
     */
    public function index()
    {
        return $this->view->fetch();
    }

    /**
     * 数据预览
     */
    public function preview()
    {
        if ($this->request->isAjax()) {
            $startDate = $this->request->get('start_date', date('Y-m-01'));
            $endDate = $this->request->get('end_date', date('Y-m-d'));
            $userId = $this->request->get('user_id', '');
            $status = $this->request->get('status', '');
            
            // 构建查询条件
            $list = $this->model;
            
            // 时间范围筛选
            if ($startDate && $endDate) {
                $startTime = strtotime($startDate);
                $endTime = strtotime($endDate . ' 23:59:59');
                if ($startTime && $endTime) {
                    $list = $list->where('createtime', 'between', [$startTime, $endTime]);
                }
            }
            
            // 员工筛选
            if ($userId && $userId !== '') {
                $list = $list->where('user_id', '=', intval($userId));
            }
            
            // 状态筛选
            if ($status !== '') {
                $list = $list->where('status', '=', intval($status));
            }
            
            // 统计信息
            $totalCount = $list->count();
            $totalQuantity = $list->sum('quantity');
            $totalWage = $list->sum('wage');
            $confirmedCount = $list->where('status', '=', 1)->count();
            
            $result = [
                'total_count' => $totalCount,
                'total_quantity' => $totalQuantity,
                'total_wage' => $totalWage,
                'confirmed_count' => $confirmedCount
            ];
            
            $this->success('', null, $result);
        }
        
        $this->error('非法请求');
    }

    /**
     * 导出明细
     */
    public function export()
    {
        // 获取搜索参数
        $startDate = $this->request->get('start_date', '');
        $endDate = $this->request->get('end_date', '');
        $userId = $this->request->get('user_id', '');
        $status = $this->request->get('status', '');
        
        // 构建基础查询
        $list = $this->model
            ->with([
                'allocation' => function($query) {
                    $query->with(['order', 'model.product', 'process']);
                },
                'user'
            ]);
        
        // 时间范围筛选
        if ($startDate && $endDate) {
            $startTime = strtotime($startDate);
            $endTime = strtotime($endDate . ' 23:59:59');
            if ($startTime && $endTime) {
                $list = $list->where('createtime', 'between', [$startTime, $endTime]);
            }
        }
        
        // 员工筛选
        if ($userId && $userId !== '') {
            $list = $list->where('user_id', '=', intval($userId));
        }
        
        // 状态筛选
        if ($status !== '') {
            $list = $list->where('status', '=', intval($status));
        }
        
        // 获取所有数据（不分页）
        $list = $list->order('id', 'desc')->select();
        
        $filename = '工资明细_' . date('Y-m-d') . '.csv';
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="' . $filename . '"');
        header('Cache-Control: max-age=0');
        
        $fp = fopen('php://output', 'w');
        
        // 输出CSV头部
        $headers = ['ID', '员工姓名', '订单号', '产品名称', '型号名称', '工序名称', '报工数量', '计件工资', '状态', '报工时间', '备注'];
        fputcsv($fp, $headers);
        
        foreach ($list as $item) {
            $row = [
                $item['id'],
                $item['user']['nickname'] ?? '-',
                $item['allocation']['order']['order_no'] ?? '-',
                $item['allocation']['model']['product']['name'] ?? '-',
                $item['allocation']['model']['name'] ?? '-',
                $item['allocation']['process']['name'] ?? '-',
                $item['quantity'],
                $item['wage'],
                $this->getStatusText($item['status']),
                date('Y-m-d H:i:s', $item['createtime']),
                $item['remark'] ?? ''
            ];
            fputcsv($fp, $row);
        }
        
        fclose($fp);
        exit;
    }

    /**
     * 导出汇总数据
     */
    public function exportSummary()
    {
        $startDate = $this->request->get('start_date', date('Y-m-01'));
        $endDate = $this->request->get('end_date', date('Y-m-d'));
        $userId = $this->request->get('user_id', '');
        $status = $this->request->get('status', '1'); // 默认只导出已确认的
        
        // 构建查询条件
        $list = $this->model->with(['user']);
        
        // 状态筛选
        if ($status !== '') {
            $list = $list->where('status', '=', intval($status));
        }
        
        // 时间范围筛选
        if ($startDate && $endDate) {
            $startTime = strtotime($startDate);
            $endTime = strtotime($endDate . ' 23:59:59');
            if ($startTime && $endTime) {
                $list = $list->where('createtime', 'between', [$startTime, $endTime]);
            }
        }
        
        // 员工筛选
        if ($userId && $userId !== '') {
            $list = $list->where('user_id', '=', intval($userId));
        }
        
        // 按员工分组统计
        $summary = $list->field('user_id, SUM(quantity) as total_quantity, SUM(wage) as total_wage, COUNT(*) as report_count')
            ->group('user_id')
            ->select();
        
        $filename = '工资汇总_' . date('Y-m-d') . '.csv';
        
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="' . $filename . '"');
        header('Cache-Control: max-age=0');
        
        // 输出CSV头部
        echo "\xEF\xBB\xBF"; // UTF-8 BOM
        echo "员工姓名,总报工数量,总工资金额,报工次数,平均工价,统计期间\n";
        
        foreach ($summary as $item) {
            $avgWage = $item['total_quantity'] > 0 ? $item['total_wage'] / $item['total_quantity'] : 0;
            $period = $startDate . ' 至 ' . $endDate;
            
            echo sprintf(
                "%s,%d,%.2f,%d,%.2f,%s\n",
                $item['user']['nickname'] ?? '未知员工',
                $item['total_quantity'],
                $item['total_wage'],
                $item['report_count'],
                $avgWage,
                $period
            );
        }
        
        exit;
    }

    /**
     * 获取状态文本
     */
    private function getStatusText($status)
    {
        $statusMap = [
            0 => '待确认',
            1 => '已确认',
            2 => '已拒绝'
        ];
        return $statusMap[$status] ?? '未知';
    }
}
